<template>
  <van-image class="avatar"
    v-bind="$attrs"
  >
    <template v-slot:loading>
      <div class="loading" :style="getTextStyle">
        {{ showText }}
      </div>
    </template>
    <template v-slot:error>
      <div class="error" :style="getTextStyle">
        {{ showText }}
      </div>
    </template>
  </van-image>
</template>

<script>

export default {
  name: 'avatar',
  props: {
    text: {
      type: String
    },
    background: {
      type: String
    },
    color: {
      type: String,
      default: 'white'
    },
    fontSize: {
      type: String,
      default: '14px'
    }
  },
  computed: {
    showText () {
      return (this.text || '')[0] || '无';
    },
    getTextStyle () {
      let index = Math.floor(Math.random() * 1000) % 5;
      let backgroundColor = [
        '#FF7700',
        '#5890F6',
        '#FFB748',
        '#55C6AD',
        '#607AF8'
      ];
      return {
        'color': this.color || 'white',
        'font-size': this.fontSize,
        'background': this.background || backgroundColor[index]
      }
    }
  }
}
</script>

<style scoped>
  .loading, .error {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
